const jwt = require('jsonwebtoken');
const uuid = require('uuid');
const redis = require('redis');

const client = redis.createClient();
client.connect();

// 生成JWT时加入盐值
function generateToken(userId, salt) {
  const payload = { userId, salt };
  const options = { expiresIn: '1h' }; // 设置过期时间
  const token = jwt.sign(payload, 'yourSecretKey', options);
  client.set(token, salt); // 将token和salt存储在Redis中
  return token;
}

// 验证JWT时检查盐值
function verifyToken(req, res, next) {
  const token = req.headers.authorization; // 获取token
  jwt.verify(token, 'yourSecretKey', (err, decoded) => {
    if (err) {
      return res.status(401).send('Unauthorized'); // JWT无效
    }
    const storedSalt = client.get(token); // 获取存储的盐值
    if (storedSalt !== decoded.salt) {
      return res.status(403).send('Forbidden'); // 盐值不匹配，拒绝访问
    }
    next(); // 盐值匹配，继续处理请求
  });
}

// https://juejin.cn/post/7433079370853449791